import os
import pytest
from aotocase_test.config import RunConfig
from selenium import webdriver


@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item,call):
    pytest_html = item.config.pluginmanager.getplugin('html')
    outcome = yield
    report = outcome.get_result()
    extra = getattr(report, 'extra', [])
    # 只获取用例运行时的结果
    if report.when == 'call':
        # always add url to report
        # extra.append(pytest_html.extras.url("http://www.example.com"))
        # 用例失败
        xfail = hasattr(report, "wasxfail")
        if (report.skipped and xfail) or (report.failed and not xfail):
            # 将测试用例的“文件名+类名+方法名”作为截图名称
            # 获取nodeid，并处理::号，替换成_
            case_path = report.nodeid.replace("::","_") + ".png"
            # only add additional html on failure
            # 还需要处理-号，叠加参数化ids，需要做判断处理
            if "[" in case_path:
                case_name = case_path.split("-")[0] + "].png"
            else:
                case_name = case_path
            # 定义方法，实现本地截图
            capture_screenshot(case_name)
            # case_name不能有/
            img_path = "images/" + case_name.split("/")[-1]
            # 如果存在img_path，向pytest_html中添加网页截图代码
            if img_path:
                html = '<div><img src="%s" alt="screenshot" style="width:304px;height:228px;">'\
                       'onclick="window.open(this.src)" align="right"</div>' % img_path
                extra.append(pytest_html.extras.html(html))
        report.extra = extra

def pytest_collection_modifyitems(items):
    """
    测试用例收集完成时，将收集到的item的name和nodeid的中文显示在控制台上
    """
    for item in items:

        item.name = item.name.encode('utf-8').decode('unicode_escape')
        item._nodeid = item.nodeid.encode('utf-8').decode('unicode_escape')

def capture_screenshot(case_name):
    """
    配置用例失败截图路径，以用例名保存图片
    :param case_name:用例名
    """
    # 使用全局变量driver
    global driver
    # 需要处理case_name,不能有/，以/为分隔符，保留最后一段
    file_name = case_name.split('/')[-1]
    # 声明图片的保存路径
    image_dir = os.path.join(RunConfig.NEW_REPORT,"image",file_name)
    # 读取配置文件里的driver，这个在用例前置中会赋值
    RunConfig.driver.save_screenshot(image_dir)

# 编写用例的前后置
@pytest.fixture(scope="session",autouse=True)
def browser():
    """
    全局定义浏览器驱动
    """
    global driver
    if RunConfig.driver_type == "chrome":
        driver = webdriver.Chrome()
    else:
        raise NameError("driver驱动类型定义错误")
    RunConfig.driver = driver

    return driver

@pytest.fixture(scope="session",autouse=True)
def browser_close():
    yield driver
    driver.quit()
    print('test end!')
